<?php
class Authlogin extends BZ_Controller
{
    public function _init()
    {
        $this->load->helper(array('api', 'common'));
        $this->load->library('alipay/authorization', null, 'authorization');
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('bind_user_model', 'bind_user');
    }
    
    public function index()
    {
        if (!$this->uid) {
            if (validateWeiXin()) {
                $openUser = $this->weChat();
            } else if(validateAliapp()) {
                $openUser = $this->aliAuth();
            } else {
                $this->load->view('home/authlogin/index');
            }
            
            if (!empty($openUser['openid']) || !empty($openUser['ali_user_id'])) {
                $result = $this->bind_user->find($openUser);
                if ($result->num_rows() > 0) {
                    $bindUser = $result->row(0);
                    $user = $this->user->findById($bindUser->uid);
                    if ($user->num_rows() > 0) {
                        $error = $this->_login($user->row(0));  //微信过来  直接登录
                    }
                } else {
                    $error = $this->createUser($openUser);
                }
                if (!empty($error)) {
                    $this->load->view('home/authlogin/error', array('error'=>$error));
                } else {
                    $this->redirect(site_url());
                }
            }
        } else {
            $this->redirect(site_url());
        }
    }
    
    /**
     * 微信授权
     */
    protected function weChat()
    {
        include_once(getcwd()."/application/libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php");
        $jsapi = new JsApi_pub();
        if (!isset($_GET['code'])) {
            $return_url = urlencode($this->config->wap_base_url.'home/authlogin/index.html');
            $url = $jsapi->createOauthUrlForCode($return_url);
            header('Location:'.$url);
        }
        
        $jsapi->setCode($_GET['code']);
        $result = $jsapi->curl($jsapi->createOauthUrlForOpenid());
        $urlOne = "https://api.weixin.qq.com/sns/userinfo?access_token=".$result->access_token."&openid=".$result->openid."&lang=zh_CN";
        $userInfo = $jsapi->curl($urlOne);
        return array('openid' => $userInfo->openid, 'personal_photo' => $userInfo->headimgurl, 'alias_name' => filterEmoji($userInfo->nickname), 'sex' => $userInfo->sex);
    }
    
    /**
     * 支付宝授权
     */
    protected function aliAuth($sid)
    {
        $authCode = $this->input->get('auth_code');
        if (empty($authCode)) {
            $return_url = $this->config->wap_base_url.'home/authlogin/index.html';
            $appid = $this->authorization->getAppid();
            $url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.$appid .'&scope=auth_userinfo&redirect_uri='. $return_url;
            header('Location:'.$url);
        }
        $params = $this->authorization->getAutoParams();
        $params['method'] = 'alipay.system.oauth.token';
        $params['code'] = $authCode;
        $params['sign'] = $this->authorization->generateSign($params, 'RSA');
        $alipayTokenResponse = json_decode($this->authorization->curl($params));
        $access_token = $alipayTokenResponse->alipay_system_oauth_token_response->access_token;
        
        return $this->getAlipayUserInfor($access_token);
    }
    
    private function  getAlipayUserInfor($auth_token)
    {
        $paramsUserInfor = $this->authorization->getAutoParams();
        $paramsUserInfor['method'] = 'alipay.user.userinfo.share';
        $paramsUserInfor['auth_token'] = $auth_token;
        $paramsUserInfor['sign'] = $this->authorization->generateSign($paramsUserInfor, 'RSA');
        $result = json_decode($this->authorization->curl($paramsUserInfor));
        $alipayUserInfor = $result->alipay_user_userinfo_share_response;
        $openUser = array(
            'ali_user_id'    => $alipayUserInfor->alipay_user_id,
            'personal_photo' => $alipayUserInfor->avatar,
            'alias_name'     => empty($alipayUserInfor->nick_name) ? '着想会员' : filterEmoji($alipayUserInfor->nick_name)
        );
        return $openUser;
    }
    
    /**
     * 用户登陆
     */
    private function _login($user)
    {
        if ($user->user_type & UTID_PROVIDER) {
            return '供应商账号不可登录哦';
        }
        if ($user->flag == 2) {
            return '此帐号已被冻结，请与管理员联系';
        }
        $userType = $this->usertype($user->user_type);
        $session = array(
            'ACT_UID'        => $user->uid,
            'ACT_UTID'       => $user->user_type,
            'ACT_TYPENAME'   => urlencode($userType['type_zh']),
            'ACT_TYPE'       => $userType['type_en'],
            'ACT_EXTRA'      => $user->extra,
            'ALIAS_NAME'     => urlencode($user->alias_name),
            'OWNER_ID'       => $user->uid,
            'OWNER_NAME'     => $user->user_name,
            'PARENT_ID'      => $user->parent_id,
            'PERSONAL_PHOTO' => urlencode($user->personal_photo),
        );
        set_cookie('frontUser', serialize($session), 3 * 24 * 3600);
        $this->cache->memcached->save('frontUser', serialize($session), 3 * 24 * 3600);
    }
    
    /**
     * 如果用户没有账号就让他注册 并登陆
     */
    private function createUser($userInfo)
    {
        $parentName = get_cookie('true_user');
        $parent_id = UTID_BEIZHU;
        $amount_bonus = 0;
        if (!empty($parentName)) {
            $parent = $this->user->validateName($parentName);
            if ($parent->num_rows() > 0) {
                $parent_id = $parent->row()->uid;
            }
        }
        $postData = array(
            'user_name'      => isset($userInfo['user_name']) ? $userInfo['user_name'] : '',
            'mobile_phone'   => isset($userInfo['mobile_phone']) ? $userInfo['mobile_phone'] : '',
            'personal_photo' => isset($userInfo['personal_photo']) ? $userInfo['personal_photo'] : '',
            'alias_name'     => isset($userInfo['alias_name']) ? $userInfo['alias_name'] : '',
            'sex_id'         => isset($userInfo['sex']) ? $userInfo['sex'] : 0,
        );
        $this->db->trans_begin(); //开启事务  开始插入数据
        $userId = $this->user->insertUser($postData, $parent_id);
        $userAccountId = $this->user_account->insertUserAccount($userId);
        if (validateWeiXin()) {
            $this->bind_user->insertBindUser(array('uid' => $userId, 'openid' => $userInfo['openid']));
        } elseif (validateAliapp()) {
            $this->bind_user->updateBindUser(array('uid' => $userId, 'ali_user_id' => $userInfo['ali_user_id']));
        }
        
        if ($this->db->trans_status() === FALSE || !$userId || !$userAccountId) {
            $this->db->trans_rollback();
            return '用户购买失败';
        } else {
            $this->db->trans_commit();
            // 注册成功了 准备登陆
            $userType = $this->usertype(UTID_CUSTOMER);
            $session = array(
                'ACT_UID'        => $userId,
                'ACT_UTID'       => UTID_CUSTOMER,
                'ACT_TYPENAME'   => urlencode($userType['type_zh']),
                'ACT_TYPE'       => $userType['type_en'],
                'ACT_EXTRA'      => 0,
                'ALIAS_NAME'     => $postData['alias_name'],
                'OWNER_ID'       => $userId,
                'OWNER_NAME'     => $postData['user_name'],
                'PARENT_ID'      => 16,
                'PERSONAL_PHOTO' => $postData['personal_photo']
            );
            set_cookie('frontUser', serialize($session), 3 * 24 * 3600);
            $this->cache->memcached->save('frontUser', serialize($session), 3 * 24 * 3600);
        }
    }
}